<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hsycms.com All rights reserved.
// | Author: 神夜 <564379992@qq.com>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_PARSE );
use PHPMailer\PHPMailer\PHPMailer;

//域名授权检测 购买授权放开此代码即可 否则检测不到
// if(!isset($_SESSION['authcode'])) {
// 	$query=file_get_contents('http://auth.hsycms.com/check.php?url='.$_SERVER['HTTP_HOST']);
// 	if($query=json_decode($query,true)) {
// 		if($query['code']==1)$_SESSION['authcode']=true;
// 		else exit('<h4>'.$query['msg'].'</h4>');
// 	}
// }

//打印函数
function p($arr){
	echo '<pre>';
	print_r($arr);
	echo '</pre>';	
}
function conversion($str){
	$data = explode(',',$str);
	$arr = ['高起专'=>'1','专升本'=>'2'];
	$str = '';
	foreach ($data as $key => $value) {
		
		$str .= array_search($value,['高起专'=>'1','专升本'=>'2']).'/';
	}
	return substr($str, 0, -1);
}
//打印SQL
function printsql($table){
	echo db($table)->getLastSql();
}

//显示textarea换行
function showTextarea($note){
	return str_replace(" "," ",str_replace("\n","<br/>",$note));
}

//订单状态
function orderStatus($status=''){
			$statusArr = [
					['status'=>0,'txt'=>'待发货','color'=>'red'],
					['status'=>1,'txt'=>'已发货','color'=>'#e2a522'],
					['status'=>2,'txt'=>'已收货','color'=>'#13b95d'],
					['status'=>3,'txt'=>'已完成','color'=>'#14e393'],
					['status'=>4,'txt'=>'已取消','color'=>'#999']
			];		
			$arr = array();
			foreach($statusArr as $key=>$v){
					if($v['status']==$status){ $arr = $v; }
			}
			return $arr;
}


//获取原图
function _getbigimg($img){
	$namearr = explode('/',$img);
	$imgname = strstr($namearr[3],'_');	 
	if($imgname!=""){ 
	  $namearr[3] = substr($imgname,1);
	  return '/upload/'.$namearr[2].'/'.$namearr[3];		 	
	}else{
	  return $img;	 
	}
}


//获取分类名
function getCateName($cid="",$nid=""){
	if($cid==""){
		$title = db('nav')->where(['id'=>$nid])->value('title');
	}else{
		$title = db('cate')->where(['id'=>$cid])->value('title');
	}
	return $title;
}

//获取文章数量
function getArticleCount($id=""){
	if($id!=""){
		return db('article')->where(['nid'=>$id])->count();
	}else{
		return null;
	}
}

//获取栏目名
function getNavName($nid=""){
	if($nid!=""){
		return db('nav')->where(['id'=>$nid])->value('title');
	}else{
		return null;
	}
}

//获取英文名称
function getEntitle($id=""){
	$nid = db('article')->where(['id'=>$id])->value('nid');
	return db('nav')->where(['id'=>$nid])->value('entitle');
}

//传入表名查询三级内容前端
function webtreelist($table='',$field="*",$where=array(),$num=''){
	$where['pid'] = 0;
	if($table=="cate"){ $where['isshow']=1; }
	$list = db($table)->field($field)->where($where)->order("sort,id")->limit($num)->select();		
	if($list){foreach($list as $key=>$v){
		$list[$key]['son'] = db($table)->field($field)->where('pid',$v['id'])->order("sort,id")->select();		
		if($list[$key]['son'])foreach($list[$key]['son'] as $key1=>$v1){
			$list[$key]['son'][$key1]['son'] = db($table)->field($field)->where('pid',$v1['id'])->order("sort,id")->select();
		}
	}}
	return $list;
}

//三级分类查询语句生成
function webtreecatewhere($cid=0){
	$catecid = array($cid);	//加入本分类	
	$where = '';		
	$sonid = db('cate')->where(['pid'=>$cid,'isshow'=>1])->field('id')->select();		
	if($sonid){
		foreach($sonid as $key=>$v){					
			  $catecid[] .= $v['id'];	//加入本分类
			  foreach($sonid as $key1=>$v1){					 
				 $son2id = db('cate')->where(['pid'=>$v1['id'],'isshow'=>1])->field('id')->select();	
				 if($son2id){
					foreach($son2id as $key2=>$v2){
						 $catecid[] .= $v2['id'];	//加入本分类
					}
				 }
			  }		
		}
		$catecid = array_flip(array_flip($catecid));  //去除数组中重复元素			
		$catecid=implode(',',$catecid);	//拆分分类ID	
		$where .= "$catecid";													
	}else{
		$where .= "$cid";				
	}		
	return $where;
}


//传入数组显示无限级分类
function treearr($arr,$id,$level){
    $list =array();
    foreach ($arr as $k=>$v){
        if ($v['pid'] == $id){
            $v['level']=$level;
            $v['son'] = treearr($arr,$v['id'],$level+1);
            $list[] = $v;
        }
    }
    return $list;
}



//截取字符串
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=false){		
		$txtdian = strlen($str) > $length ? '...' :'';
	 if(function_exists("mb_substr")){
	  if($suffix)
	   return mb_substr($str, $start, $length, $charset).$txtdian;
	  else
	   return mb_substr($str, $start, $length, $charset);
	 }elseif(function_exists('iconv_substr')) {
	  if($suffix)
	   return iconv_substr($str,$start,$length,$charset).$txtdian;
	  else
	   return iconv_substr($str,$start,$length,$charset);
	 }
	 $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
	 $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
	 $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
	 $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
	 preg_match_all($re[$charset], $str, $match);
	 $slice = join("",array_slice($match[0], $start, $length));
	 if($suffix) return $slice.$txtdian;
	 return $slice;
}

//二维数组去掉重复值
function array_unique_fb($array2D){
    foreach ($array2D as $v)
    {
        $v = join(",",$v);  //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    
    $temp = array_unique($temp);   //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v)
    {
        $temp[$k] = explode(",",$v);  //再将拆开的数组重新组装
    }
    return $temp;
}

//发邮件
function sendemail($data){
   $mail = new PHPMailer();
	  try{
		  //邮件调试模式
		  $mail->SMTPDebug = 0;  
		  //设置邮件使用SMTP
		  $mail->isSMTP();
		  // 设置邮件程序以使用SMTP
		  $mail->Host = config('email_host');
		  // 设置邮件内容的编码
		  $mail->CharSet='UTF-8';
		  // 启用SMTP验证
		  $mail->SMTPAuth = true;
		  // SMTP username
		  $mail->Username = config('email_send_name');
		  // SMTP password
		  $mail->Password = config('email_send_pass');
		  // 启用TLS加密，`ssl`也被接受
		  //$mail->SMTPSecure = 'tls';
		  if(config('email_smtpsecure')!=""){
		  	$mail->SMTPSecure = config('email_smtpsecure');
		  }
		  // 连接的TCP端口
		  $mail->Port = config('email_port');
		  //设置发件人
		  $mail->setFrom(config('email_send_name'), config('webtitle'));
		  //网站管理后台添加收件人1
		  $mail->addAddress(config('email_form'), config('email_form_name'));     // Add a recipient
		  //$mail->addAddress('ellen@example.com');               // Name is optional
		  //收件人回复的邮箱
		  $mail->addReplyTo($data['email'], $data['name']); //网页端客户的邮箱地址，客户的姓名字
		  //抄送
		  //$mail->addCC('cc@example.com');
		  //$mail->addBCC('bcc@example.com');
		  //附件
		  //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
		  //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
		  //Content
		  // 将电子邮件格式设置为HTML
		  $mail->isHTML(true);
		  $mail->Subject = $data['title'];
		  $mail->Body    = $data['content'];
		  //$mail->AltBody = '这是非HTML邮件客户端的纯文本';
		  $mail->send();
		  //echo 'Message has been sent';
		  //$mail->isSMTP();
	  }catch (Exception $e){
		  echo 'Mailer Error: ' . $mail->ErrorInfo;
	  }
} 


//获取蜘蛛爬虫痕迹
function spider(){
	$ax_ym  = $_SERVER['REQUEST_URI'];
	$ax_ss  = $_SERVER['HTTP_USER_AGENT'];
	$ax_url = $_SERVER['HTTP_REFERER'];
	$ax_ip  = $_SERVER['HTTP_X_FORWARDED_FOR'];
	if(empty($ax_ip)){
		$ax_ip = $_SERVER['REMOTE_ADDR'];
	}	
	$baidu=stristr($ax_ss,"Baiduspider");
	$google=stristr($ax_ss,"Googlebot");
	$soso=stristr($ax_ss,"Sosospider");
	$youdao=stristr($ax_ss,"YoudaoBot");
	$bing=stristr($ax_ss,"bingbot");
	$sogou=stristr($ax_ss,"Sogou web spider");
	$yahoo=stristr($ax_ss,"Yahoo! Slurp");
	$Alexa=stristr($ax_ss,"Alexa");
	$so=stristr($ax_ss,"360Spider");
	if($baidu)
	{
		$ax_ss="baidu";
	}
	elseif($google)
	{
		$ax_ss="Google";
	}
	elseif($soso)
	{
		$ax_ss="soso";
	}
	elseif($youdao)
	{
		$ax_ss="youdao";
	}
	elseif($bing)
	{
		$ax_ss="bing";
	}
	elseif($sogou)
	{
		$ax_ss="sogou";
	}
	elseif($yahoo)
	{
		$ax_ss="yahoo";
	}
	elseif($Alexa)
	{
		$ax_ss="Alexa";
	}
	elseif($so)
	{
		$ax_ss="so";
	}
	else
	{
		$ax_ss=null;
	}
	$data['title']    = $ax_ss;	
	$data['url']      = $ax_ym;
	$data['oldurl']   = $ax_url;
	$data['ip']       = $ax_ip;
	$data['datetime'] = time();
	if($baidu or $google or $soso or $youdao or $bing or $sogou or $yahoo or $Alexa or $so)
	{
		$res = db('spider')->insert($data);
	}
}


//网站SEO
function getseo($nid='', $id='', $cid='')
{
    $site['webtitle'] = config('webtitle');
    $site['webkeywords'] = config('webkeywords');
    $site['webdescription'] = config('webdescription');
    if ($nid!="") {
        $seo = db('nav')->where(["id"=>$nid])->find();
        $site['webtitle']    	= $seo['seo_title']==""?$seo['title'].'-'.config('webtitle'):$seo['seo_title'];
        $site['webkeywords'] 	= $seo['seo_keywords']==""?config('webkeywords'):$seo['seo_keywords'];
        $site['webdescription'] = $seo['seo_description']==""?config('webdescription'):$seo['seo_description'];
            
        if ($id!="" && $cid=="") {									   
            $c = db('article')->where("id", $id)->find();
												
						$webtitle = $site['webtitle'] == "" ? config('webtitle') : $site['webtitle'];
						$webkeywords = $site['webkeywords'] == "" ? config('webkeywords') : $site['webkeywords'];
						$webdescription = $site['webdescription'] == "" ? config('webdescription') : $site['webdescription'];
												
            $site['webtitle']       = $c['seo_title']==""?$c['title'].'-'.$webtitle:$c['seo_title'];
            $site['webkeywords']    = $c['seo_keywords']==""?$webkeywords:$c['seo_keywords'];
            $site['webdescription'] = $c['seo_description']==""?$webdescription:$c['seo_description'];
        }
                        
        if ($cid!="" && $id=="") {
            $c = db('cate')->where("id", $cid)->find();
            $site['webtitle']       = $c['seo_title']==""?$c['title'].'-'.config('webtitle'):$c['seo_title'];
            $site['webkeywords']    = $c['seo_keywords']==""?config('webkeywords'):$c['seo_keywords'];
            $site['webdescription'] = $c['seo_description']==""?config('webdescription'):$c['seo_description'];
        }
            
        if ($cid!="" && $id!="") {
            $c = db('cate')->where("id", $cid)->find();
            $l = db('article')->where("id", $id)->find();
												
						$webtitle = $site['webtitle'] == "" ? config('webtitle') : $site['webtitle'];
						$webkeywords = $site['webkeywords'] == "" ? config('webkeywords') : $site['webkeywords'];
						$webdescription = $site['webdescription'] == "" ? config('webdescription') : $site['webdescription'];												
												
            $site['webtitle']       = $l['seo_title']==""?$l['title'].'-'.$webtitle:$l['seo_title'];
            $site['webkeywords']    = $l['seo_keywords']==""?$webkeywords:$l['seo_keywords'];
            $site['webdescription'] = $l['seo_description']==""?$webdescription:$l['seo_description'];
        }
    }
    return $site;
}


//判断是否手机访问
function isMobile()
{ 
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    } 
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    { 
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    } 
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
            ); 
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        } 
    } 
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    { 
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        } 
    } 
    return false;
} 
 


//导航
function nav(){
	$list = db('nav')->where('isshow=1')->field('showcate,id,title,entitle')->order('sort,id')->select();
	if($list){
		foreach($list as $key=>$v){				
			$list[$key]['link'] = u($v['entitle']);				
			if($v['showcate']==1){
				$list[$key]['son'] = db('cate')->where("nid=".$v['id']." and isshow=1 and pid=0")->field('id,title,entitle')->order("sort,id")->select();
				if($list[$key]['son'])foreach($list[$key]['son'] as $key1=>$v1){						
					$list[$key]['son'][$key1]['link'] = isMobile() ? u($v1['entitle'],'',1) : u($v1['entitle']);
				}
			}else{
				$list[$key]['son'] = db('article')->where("nid=".$v['id'])->field('title,id')->order("sort,id")->select();
				if($list[$key]['son'])foreach($list[$key]['son'] as $key2=>$v2){
					$list[$key]['son'][$key2]['link'] = isMobile() ? u($v['entitle'],$v2['id'],1) : u($v['entitle'],$v2['id']);
				}
			}
		}
	}
	return $list;		
}


//获取栏目ID参数
function getNID(){
	$url =  request()->url();
	$url = str_replace('/','',$url);
	if(strpos($url,'?')!==false){
		$url = explode('?',$url);
		$url = $url[0];
	}
	return $url;
}

//获取上下篇
function prevNext($id="",$entitle="",$one="",$mbispc=0){ 
	  //上一篇
	  $pmap['id']  = array('lt',$id);
	  $pmap['nid'] = $one['nid'];
	  $pmap['cid'] = $one['cid'];
	  $prev=db('article')->field("id,title")->where($pmap)->order('id desc')->limit('1')->find();  
	  if($prev){		  
		  $prev['url'] = u($entitle,$prev['id'],$mbispc);
	  }else{
		  $prev['url'] = "javascript:void(0)";
		  $prev['title'] = "没有了";
	  }
	  $data['prev'] = $prev; 
	  
	  //下一篇
	  $nmap['id']  = array('gt',$id);
	  $nmap['nid'] = $one['nid'];
	  $nmap['cid'] = $one['cid'];
	  $next = db('article')->field("id,title")->where($nmap)->order('id asc')->limit('1')->find();  
	  if($next){
		  $next['url'] =  u($entitle,$next['id'],$mbispc);
	  }else{
		  $next['url'] = "javascript:void(0)";
		  $next['title'] = "没有了";
	  }
	  $data['next'] = $next;
	  return $data;
}

/**
* 获取当前模板文件
* @return array 文件列表
*/
function tplList($default_themes)
{
	$tplDir=APP_PATH.'/index/view/'.$default_themes;
	if(!is_dir($tplDir)){
		return false;
	}
	$listFile=scandir($tplDir);
	if(is_array($listFile)){
		$list=array();
		foreach ($listFile as $key => $value) {
			if ($value != "." && $value != "..") {
				$list[$key]['file']=$value;
				$list[$key]['name']=substr($value, 0, -5);
			}
		}
	}
	return $list;
}

	
function replaceContentImgUrl($content) {
  $url = substr(config('weburl'),0,-1);
  $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
  $content = preg_replace($pregRule, '<img src="'.$url.'${1}" style="max-width:100%">', $content);
  return $content;
}


function getRandomString($len, $chars=null)
{
    if (is_null($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyz";
    }
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

//订单号生成
function getRandomNumber($len, $chars=null)
{
    if (is_null($chars)) {
        $chars = "0123456789";
    }
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

//输出
function result($code,$msg,$data){
	   exit(json_encode(['code'=>$code,'msg'=>$msg,'data'=> $data]));
}

//curl
function curl_get($url, &$httpCode = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}

//生成拼接URL
function ToUrlParams($data)
{
	$buff = "";
	foreach ($data as $k => $v)
	{
		if($k != "sign" && $v != "" && !is_array($v)){
			$buff .= $k . "=" . $v . "&";
		}
	}
	
	$buff = trim($buff, "&");
	return $buff;
}

/**
 * 生成签名
 */
function MakeSign($data,$key)
{	
	//p($data);
	//签名步骤一：按字典序排序参数
	ksort($data);
	$string = ToUrlParams($data);	
	//签名步骤二：在string后加入KEY
	$string = $string . "&key=".$key;
	//echo $string;
	//签名步骤三：MD5
	$string = md5($string);	
	//签名步骤四：所有字符转为大写
	$result = strtoupper($string);
	return $result;
}

//日志记录
function writeLog($title,$content){
	  $d['title'] = $title;
			$d['content'] = $content;
			$d['datetime'] = date('Y-m-d H:i:s',time());
	  db('log')->insert($d);
}

//加密函数
function lock_key($txt, $key='str')
{
		$txt = $txt.$key;
		$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
		$nh = rand(0, 64);
		$ch = $chars[$nh];
		$mdKey = md5($key.$ch);
		$mdKey = substr($mdKey, $nh%8, $nh%8+7);
		$txt = base64_encode($txt);
		$tmp = '';
		$i=0;
		$j=0;
		$k = 0;
		for ($i=0; $i<strlen($txt); $i++) {
				$k = $k == strlen($mdKey) ? 0 : $k;
				$j = ($nh+strpos($chars, $txt[$i])+ord($mdKey[$k++]))%64;
				$tmp .= $chars[$j];
		}
		return urlencode(base64_encode($ch.$tmp));
}

//解密函数
function unlock_key($txt, $key='str')
{
		$txt = base64_decode(urldecode($txt));
		$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
		$ch = $txt[0];
		$nh = strpos($chars, $ch);
		$mdKey = md5($key.$ch);
		$mdKey = substr($mdKey, $nh%8, $nh%8+7);
		$txt = substr($txt, 1);
		$tmp = '';
		$i=0;
		$j=0;
		$k = 0;
		for ($i=0; $i<strlen($txt); $i++) {
				$k = $k == strlen($mdKey) ? 0 : $k;
				$j = strpos($chars, $txt[$i])-$nh - ord($mdKey[$k++]);
				while ($j<0) {
						$j+=64;
				}
				$tmp .= $chars[$j];
		}
		return trim(base64_decode($tmp), $key);
}

/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function diffBetweenTwoDays ($start_time, $end_time)
{
  for($i = $start_time; $i <=$end_time; $i+=86400)
  {
      $days[] =strtotime(date('Y-m-d',$i));
  }
  $count_days = count($days);
		return $count_days;
}

//设置优惠券是否过期
function checkCouponUse($id,$endtime){
	  $day1 = date('Y-m-d',time());
			$day2 = date('Y-m-d',strtotime($endtime));
	  $day	= diffBetweenTwoDays($day1,$day2);		
		 if($day == 0){
				  db('memcoupon')->where(['id'=>$id])->setField(['use'=>2]);
			}
}

//24小时订单自动取消
function orderAutoCancel($id,$createtime){
	  $curtime   = time();
	  $createtime = strtotime($createtime)+60*60*24; 
	  if($curtime > $createtime){
	  	  db('order')->where(['id'=>$id,'paystate'=>0,'status'=>0])->setField(['status'=>4]);
	  }
}


//发送短信 吉通信
function sendMobileCode($mobile, $msg)
{
    $url="http://service.winic.org:8009/sys_port/gateway/index.asp?	";
    $data = "id=%s&pwd=%s&to=%s&content=%s&time=";
    $id = ''; 
    $pwd = '';
    $to = $mobile;
    $content = iconv("UTF-8", "GB2312", $msg);
    $rdata = sprintf($data, $id, $pwd, $to, $content);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $rdata);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = substr($result, 0, 3);
    return $result;
}

//生成数字随机数
function GetRandNumStr($length)
{
    $str='0123456789';
    $len=strlen($str)-1;
    $randstr='';
    for ($i=0;$i<$length;$i++) {
        $num=mt_rand(0, $len);
        $randstr .= $str[$num];
    }
    return $randstr;
}

//发送验证码
function sendCode($mobile)
{	
   if ($mobile!="") {
				if(time() - session('sendCodeTime') > 60){
				$code = GetRandNumStr(6);
				session('MobileCode', $code);
				$content = '您的手机验证码为：'.$code.'。请注意查收！';
				$result = sendMobileCode($mobile, $content);
				if ($result=='000') {
					session('sendCodeTime',time());
					exit(json_encode(['code'=>1,'msg'=>'短信发送成功']));
			 } else {
				switch ($result) {
					case '-01':
					$result = '账号余额不足';
					break;
					case '-02':
					$result = '未开通接口授权';
					break;
					case '-03':
					$result = '账号密码错误';
					break;
					case '-04':
					$result = '参数个数不对或者参数类型错误';
					break;
					case '-110':
					$result = 'IP被限制';
					break;			
					case '-12':
					$result = '其他错误';
					break;
				}
				exit(json_encode(['code'=>0,'msg'=>$result]));
			}
		}else{
				exit(json_encode(['code'=>0,'msg'=>'请稍后再试!']));	
		}
		} else {
				exit(json_encode(['code'=>0,'msg'=>'手机号码不能为空']));
		}
}


//获取分类英文名
function getCateEntitle($cid){
	return db('cate')->where('id',$cid)->value('entitle');
}

//将内容中图片的相对路径替换为绝对路径
function pregReplaceImgurl($content,$prefix){		
		$contentAlter = preg_replace_callback('/(<[img|IMG].*?src=[\'\"])([\s\S]*?)([\'\"])[\s\S]*?/i', function($match)use($prefix){				
				if(!strstr($match[2], 'http://') && !strstr($match[2], 'https://')){
					return $match[1].$prefix.$match[2].$match[3];
				}else{
					return $match[1].$match[2].$match[3];
				}
		} , $content);
		return $contentAlter;
}
